package com.example.wacoffee_user.service.Impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.wacoffee_user.constants.MQConstants;
import com.example.wacoffee_user.mapper.OrderMapper;
import com.example.wacoffee_user.pojo.dto.OrderPayDTO;
import com.example.wacoffee_user.pojo.entity.Good;
import com.example.wacoffee_user.pojo.entity.Order;
import com.example.wacoffee_user.pojo.entity.coupon;
import com.example.wacoffee_user.pojo.entity.item;
import com.example.wacoffee_user.pojo.vo.pointVo;
import com.example.wacoffee_user.service.IOrderService;
import com.example.wacoffee_user.utils.CurrentHoler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    private final RabbitTemplate rabbitTemplate;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String addOrder(Order order) {
        List<item> list = orderMapper.checkStock(order.getItems());
        for(item i:list){
            if(i.getQuantity()<1)throw new RuntimeException(i.getGoodName()+"库存不足，试试别的吧＞﹏＜");
        }
        for(item i:order.getItems()){
            if(i.getQuantity()<0)throw new RuntimeException("商品数量出错了");
            for(item good:list){
                if(good.getGoodId()==i.getGoodId()){
                    if(good.getQuantity()<i.getQuantity()){
                        throw new RuntimeException(good.getGoodName()+"库存不足，试试别的吧＞﹏＜");
                    }
                   }
            }
        }
        order.setUserId(CurrentHoler.getCurrentId());
        orderMapper.saveOrder(order);
        int orderId=order.getId();
        orderMapper.batchDeductStock(order.getItems());
        orderMapper.addOrderToGoods(order.getItems(),orderId);
        rabbitTemplate.convertAndSend(
                MQConstants.DELAY_EXCHANGE_NAME,
                MQConstants.DELAY_ORDER_KEY,
                orderId,
                message -> {
                    message.getMessageProperties().setDelayLong(1000*60*5L);
                    return message;
                }
        );
        return "下单成功,订单编号:"+orderId;
    }

    @Override
    public List<Order> getAllOrder() {
        return orderMapper.getAllOrder(CurrentHoler.getCurrentId());
    }

    @Override
    public List<Order> getNoPaidOrder() {
        return orderMapper.getNoPaidOrder(CurrentHoler.getCurrentId());
    }

    @Override
    public List<Order> getProcessedOrder() {
        return orderMapper.getProcessedOrder(CurrentHoler.getCurrentId());
    }

    @Override
    public List<Order> getCanceledOrder() {
        return orderMapper.getCanceledOrder(CurrentHoler.getCurrentId());
    }

    @Override
    @Transactional
    public void payOrder(OrderPayDTO order) {
        if(order.getCouponId()!=null){
            orderMapper.updateCouponStatus(order.getUid().intValue());
            coupon coupon=orderMapper.getCouponById(Math.toIntExact(order.getCouponId()));
            if(coupon.getStatus()!=1)throw new RuntimeException("优惠券状态异常");
            if(coupon.getMinAmount()>order.getExpend())throw new RuntimeException("优惠券使用条件未达到");
            order.setExpend(order.getExpend()-coupon.getValue());
        }
        int result = orderMapper.updateUserBalance(order.getExpend(), order.getUserId());
        if(result!=1)throw new RuntimeException("支付行为出现异常了,请检查余额");
        orderMapper.payOrder(Math.toIntExact(order.getId()));
        rabbitTemplate.convertAndSend("point.direct","point.success",new pointVo(order.getUserId(),order.getExpend()));
    }

    @Override
    public void cancelPay(int orderId){
        List<Good> goods=orderMapper.getGoodsByOrderId(orderId);
        orderMapper.updateGoodStock(goods);
        UpdateWrapper<Order> updateWrapper=new UpdateWrapper<>();
        updateWrapper.set("status",2).eq("id",orderId);
        orderMapper.update(updateWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addPoint(pointVo pointVo) {
        orderMapper.addPoint(pointVo);
        int success = orderMapper.checkExp(pointVo.getUserId());
        if(success==1)orderMapper.addLevelCoupon(pointVo.getUserId(),53);
    }

}
